<script setup>
import { Modal } from 'ant-design-vue'
import { CaretDownFilled, CheckCircleOutlined, ColumnHeightOutlined, DeleteOutlined, DoubleRightOutlined, DownOutlined, EditOutlined, KeyOutlined, LockOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UndoOutlined, UpOutlined } from '@ant-design/icons-vue'
import { getBoxList, giftDetail, getGiftList, exportCard, getHospitalList, addGiftCard, getTotalInfo } from '~@/api/gift/index'
import { getMerchantList } from '~@/api/card/index'

defineOptions({
  name: 'Gift',
})
// 新增角色
const roleForm = ref()
const userTitle = shallowRef('')
const cardOpen = ref(false)
const giftOpen = ref(false)
const giftLoading = ref(false)
const allocateLoading = ref(false)
const editInfo = reactive({
  roleId: null,
})
const totalInfo = shallowRef({
  batchSum: 0,
  totalSum: 0,
  storageSum: 0
})

const confirmLoading = ref(false) //确认加载中
// 分配菜单
const menuOpen = ref(false)
const plainOptions = shallowRef([])
// const checkedList = ref([])
// const checkAll = ref(false)
const menuState = reactive({
  indeterminate: true,
  checkAll: false,
  checkedList: [],
})
// const indeterminate = ref(false)
// 分配功能
const funcOpen = ref(false)
const detailId = ref(null)
const funcOptions = shallowRef([])
const funcState = reactive({
  indeterminate: true,
  checkAll: false,
  checkedList: [],
})
const funcInfo = reactive({
  roleId: null,
})
// 数据权限
const dataOpen = ref(false)
const dataOptions = shallowRef([])
const dataState = reactive({
  indeterminate: true,
  checkAll: false,
  checkedList: [],
})
const dataInfo = reactive({
  roleId: null,
})
const rules = computed(() => {
  return {
    faceAmount: [
      { required: true, message: '请填写面额', trigger: 'change' },
    ],
    total: [
      { required: true, message: '请填写预占张数', trigger: 'change' },
    ],
    saleAppId: [
      { required: true, message: '请选择售卖商家', trigger: 'change' },
    ],
    useAppIdList: [
      { required: true, message: '请选择使用商家', trigger: 'change' },
    ],
    batchIntro: [
      { required: true, message: '请填写批次说明', trigger: 'change' },
    ],
  }
})
const options = ref([])
const saleOptions = ref([])

const statusOptions = ref([
  {
    value: '',
    label: '全部',
  },
  {
    value: 'INIT',
    label: '库存',
  },
  {
    value: 'ACTIVE',
    label: '已登记',
  },
])
const formState = reactive({
  cardType: '',
  faceAmount: '',
  total:'',
  saleAppId:null,
  useAppIdList:[],
  batchIntro:''
})
const salesState = reactive({
  cardNo: '',
  status: '',

})
const giftInfo = reactive({
  remarks: '',
})

const message = useMessage()
const selectedRowKeys = shallowRef([])
const giftData = shallowRef([])
const giftDetailData = shallowRef([])

const columns = shallowRef([
  {
    title: '批次说明',
    dataIndex: 'batchIntro',
    width: 200,
    ellipsis: true
  },
  {
    title: '起始卡号',
    dataIndex: 'cardNoStart',
    width: 200,
  },

  {
    title: '面额',
    dataIndex: 'faceAmount',
    width: 150,

  },
  {
    title: '张数',
    dataIndex: 'total',
    width: 100,

  },
  {
    title: '售卖商家',
    dataIndex: 'saleAppName',
    width: 200,

  },
  {
    title: '使用商家',
    dataIndex: 'useAppNameList',
    width: 200,
    ellipsis: true,
    render: arr => arr.map(item => item).join(',')

  },
  {
    title: '已登记',
    dataIndex: 'activeCount',
    width: 100,

  },
  {
    title: '库存',
    dataIndex: 'storedCount',
    width: 100,

  },
  {
    title: '建卡日期',
    dataIndex: 'createTime',
    width: 200,

  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: '180px',

  },
])
const giftColumns = shallowRef([
  {
    title: '卡号',
    dataIndex: 'cardNo',
    width: 300,
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 300,
    customRender: ({ text }) => {
      if (text === 'INIT') {
        return '库存'
      }
      else {
        return '已登记'
      }
    },
  },
  {
    title: '登记时间',
    dataIndex: 'activeTime',
    customRender: ({ text }) => {
      if (text) {
        return text
      }
      else {
        return '--'
      }
    },
  },

])
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const totalDetailNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const cardPagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalDetailNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    cardPagination.pageSize = pageSize
    cardPagination.current = current
    getSalesName()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  roleName: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)

const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
onMounted(() => {
  init()
  getAppName()
  getTotal()
  getHospital()
  
})

// 获取医院名称
async function getAppName() {
  const { data } = await getMerchantList()
  const appData = data?.map(item=>({
    value:item.appId,
    label:item.appName
  }))
  options.value = appData
  
};

// 获取统计信息
async function getTotal() {
  const { data } = await getTotalInfo(formModel)
  totalInfo.value = data
  
};

// 查询礼品列表
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getBoxList({
      param: { ...formModel },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
function handleChange(value) {
  console.log(`selected ${value}`)
}
function handleBlur() {
  console.log('blur')
}
function handleFocus() {
  console.log('focus')
}
function filterOption(input, option) {
  return option.label.toLowerCase().includes(input.toLowerCase())
}
// 搜索
async function onSearch() {
  pagination.current = 1
  await init()
  await getTotal()
}
// 导出
async function exportExcel(record) {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await exportCard(record.id)
    if(data.url){
      window.location.href = data.url
    }
    
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

// 查看礼品表信息详情
async function handleView(record) {
  loading.value = true
  giftInfo.remarks = record.remarks
  detailId.value = record.id
  getSalesName()
}
// 查看批次详情列表
async function getSalesName() {
  giftLoading.value = true
  try {
    salesState.batchId = detailId
    const { data } = await getGiftList({
      param: { ...salesState },
      page: {
        currentPage: cardPagination.current,
        pageSize: cardPagination.pageSize,
      },

    })
    giftOpen.value = true
    giftDetailData.value = data.data
    totalDetailNum.value = data?.pageInfo.total
    giftLoading.value = false
    loading.value = false

  }
  catch (error) {
    giftLoading.value = false
    giftOpen.value = false
    console.log(3333, error)
  }
  finally {
    loading.value = false
  }
  
};
// 获取售卖商家列表
async function getHospital() {
  try {
    const { data } = await getHospitalList()
    const appData = data?.map(item=>({
      value:item.appId,
      label:item.appName
    }))
    saleOptions.value = appData
  }
  catch (error) {

  }
  finally {

  }
  
};

// 创建礼品卡
function addRoleModal() {
  if (roleForm.value) {
    roleForm.value.resetFields()
  }
  resetCard()
  userTitle.value = '创建礼品卡'
  cardOpen.value = true
}
// 确认创建礼品卡
async function handleOk() {
  confirmLoading.value = true
  try {
    await roleForm.value.validate()
      const { data } = await addGiftCard(formState)
      if (data.code === 'SUCCESS') {
        confirmLoading.value = false
        cardOpen.value = false
        message.success('新增成功')
        init()
      }else{
        confirmLoading.value = false
      }
    
  }
  catch (error) {
    confirmLoading.value = false
    // message.error('请检查表单填写是否正确')
  }
}
// 处理使用商家
function handleHospital(record){
 return record.map(item=>item).join('、')
}

// 重置礼品卡信息
function resetCard() {
  formState.roleId = void 0
  formState.roleName = void 0
  formState.roleType = void 0
  formState.memo = void 0
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
watch(
)
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :model="formModel" layout="inline">
        <a-form-item name="batchIntro" label="批次说明">
          <a-input v-model:value="formModel.batchIntro" placeholder="批次说明" allow-clear />
        </a-form-item>
        <a-form-item name="saleAppId" label="售卖商家">
          <a-select
            v-model:value="formModel.saleAppId"
            allow-clear
            show-search
            placeholder="请输入关键字搜索"
            style="width: 330px"
            :options="options"
            :filter-option="filterOption"
            @focus="handleFocus"
            @blur="handleBlur"
            @change="handleChange"
          />
        </a-form-item>
        <a-form-item>
          <a-space flex justify-end w-full>
            <a-button type="primary" @click="onSearch">
              <SearchOutlined />查询
            </a-button>
            <a-button type="primary" class="ml-2" ghost @click="addRoleModal">
              <PlusOutlined />创建礼品卡
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <div class="mt-5 font-600" style="background:#f5f5f5;padding:10px;margin-bottom:-8px;">
        共计制卡 <span>{{ totalInfo.batchSum }}</span> 批，共 <span>{{ totalInfo.totalSum }}</span> 张，库存 <span>{{ totalInfo.storageSum }}</span> 张。
      </div>
    </a-card>

    <a-card>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'faceAmount'">
            <span>{{ Number(record.faceAmount).toFixed(2) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'useAppNameList'">
            {{ handleHospital(record.useAppNameList)}}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <div class="action flex flex-center">
              <a @click="handleView(record)">查看</a>
              <span class="middle-line">|</span>
              <a @click="exportExcel(record)">导出</a>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 新增礼品卡 -->
    <a-modal v-model:open="cardOpen" :mask-closable="false" width="900px" :title="userTitle" :body-style="{ paddingTop: '25px', paddingBottom: '30px' }" ok-text="确定" @ok="handleOk" :confirm-loading="confirmLoading">
      <a-form
        ref="roleForm"
        :model="formState"
        :rules="rules"
        name="basic"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item name="faceAmount" label="面额(元)">
              <a-input v-model:value="formState.faceAmount" placeholder="面额" allow-clear />
            </a-form-item>
            <a-form-item name="total" label="预占张数">
              <a-input v-model:value="formState.total" placeholder="预占张数" allow-clear />
            </a-form-item>
            <a-form-item  name="saleAppId" label="售卖商家">
              <a-select
                  v-model:value="formState.saleAppId"
                  show-search
                  placeholder="请选择售卖商家"
                  :options="saleOptions"
                  :filter-option="filterOption"
                  @focus="handleFocus"
                  @blur="handleBlur"
                  @change="handleChange"
                ></a-select>
            </a-form-item>
            <a-form-item  name="useAppIdList" label="使用商家">
              <a-select
                  v-model:value="formState.useAppIdList"
                  show-search
                  mode="multiple"
                  placeholder="请选择使用商家"
                  :options="saleOptions"
                  :filter-option="filterOption"
                  @focus="handleFocus"
                  @blur="handleBlur"
                  @change="handleChange"
                ></a-select>
            </a-form-item>
            <a-form-item name="batchIntro" label="批次说明">
              <a-textarea v-model:value="formState.batchIntro" placeholder="批次说明" :rows="4" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <!-- 查看礼品卡信息列表 -->
    <a-modal v-model:open="giftOpen" :footer="null" :mask-closable="false" width="1000px"  :title="giftInfo.remarks" :body-style="{ height: '570px', paddingTop: '25px', paddingBottom: '50px' }">
      <a-form :model="salesState" layout="inline" class="mb-8">
        <a-form-item label="卡号">
          <a-input v-model:value="salesState.cardNo" placeholder="精确查询" allow-clear />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="salesState.status"
            allow-clear
            placeholder="请选择"
            style="width: 200px"
            :options="statusOptions"
          />
        </a-form-item>
        <a-form-item>
          <a-space flex justify-end w-full>
            <a-button type="primary" @click="getSalesName">
              <SearchOutlined />查询
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <a-table row-key="roleId" bordered :loading="giftLoading"  :columns="giftColumns" :data-source="giftDetailData" :pagination="cardPagination"/>
    </a-modal>
  </page-container>
</template>

    <style lang="less" scoped>
      :deep(.ant-btn){
        padding: 4px 8px;
      }
      .ant-divider-horizontal{
        margin: 15px 0;
      }
      .line{
        color:#1677ff;
      }
      .userTitle{
        color:gray;
        width: 100%;
        padding:5px 0;
        border-bottom:1px solid #f1eded;
        margin-bottom: 20px;
      }
      .red{
        color:red;
        /* color:#ff4d4f; */
      }
      .card-title{
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        flex: auto;
        color: rgba(0, 0, 0, 0.88);
        font-weight: 600;
        font-size: 16px;
        line-height: 1.5;
      }
    @media screen and (max-width: 1200px) and (min-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        margin-left: -44px;
        .statItem {
          padding: 0 16px;
        }
      }
    }

    @media screen and (max-width: 992px) {
      .activeCard {
        margin-bottom: 24px;
      }
      .members {
        margin-bottom: 0;
      }
      .extraContent {
        float: none;
        margin-right: 0;
        .statItem {
          padding: 0 16px;
          text-align: left;
          &::after {
            display: none;
          }
        }
      }
    }

    @media screen and (max-width: 768px) {
      .extraContent {
        margin-left: -16px;
      }
      .projectList {
        .projectGrid {
          width: 50%;
        }
      }
    }

    @media screen and (max-width: 576px) {
      .pageHeaderContent {
        display: block;
        .content {
          margin-left: 0;
        }
      }
      .extraContent {
        .statItem {
          float: none;
        }
      }
    }

    @media screen and (max-width: 480px) {
      .projectList {
        .projectGrid {
          width: 100%;
        }
      }
    }
    </style>

    <style>
      [class^="ant-checkbox-group"] [class*=" ant-checkbox-group"]{
        margin:10px !important;
        width:190px !important;
      }
</style>
